package com.yxw.live_vod_boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_boot.dto.PageUserListDto;
import com.yxw.live_vod_boot.dto.UpdateUserDTO;
import com.yxw.live_vod_boot.dto.UpdateUserPayPwdDTO;
import com.yxw.live_vod_boot.entity.*;
import com.yxw.live_vod_boot.mapper.*;
import com.yxw.live_vod_boot.service.FileService;
import com.yxw.live_vod_boot.service.UserService;
import com.yxw.live_vod_boot.utils.HuaWeiObsUtil;
import com.yxw.live_vod_boot.utils.PageUtils;
import com.yxw.live_vod_boot.utils.RedisManager;
import com.yxw.live_vod_boot.utils.UserUtil;
import com.yxw.live_vod_boot.vo.UserInfoVo;
import com.yxw.live_vod_boot.vo.YxFileVo;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.CommonErrorEnum;
import com.yxw.yxnet_cd_center.common.enums.FileClassifyEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.PasswordUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 平台人员管理
 * @author liuxin
 * @date 2023.12.1
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, YxSysUserEntity> implements UserService {


    @Autowired
    private FileService fileService;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private HuaWeiObsUtil  huaWeiObsUtil;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private UserCancelMapper userCancelMapper;

    @Autowired
    private ShopCancelMapper shopCancelMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHeaderImage(MultipartFile headImage, Long userId) {
        //先查询是否已经上传头像
        LambdaQueryWrapper<YxFileEntity> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(true,YxFileEntity::getBussId,userId);
        YxFileEntity fileEntity = fileMapper.selectOne(queryWrapper);
        //先上传头像
        MultipartFile[] multipartFiles=new MultipartFile[]{headImage};
        List<YxFileVo> yxFileVos = fileService.uploadFile(multipartFiles, userId, FileClassifyEnum.IMAGES_FILE.getCode(), "");
        //查询人员信息
        YxSysUserEntity userEntity = baseMapper.selectById(userId);
        if(null==userEntity){
            throw new BaseException("修改头像失败,人员不存在");
        }
        userEntity.setHeadUrl(yxFileVos.get(0).getFileUrl());
        baseMapper.updateById(userEntity);
        //这里删除原有头像
        if(null!=fileEntity){
            //删除文件数据
            fileMapper.deleteById(fileEntity.getId());
            //删除华为云文件
            huaWeiObsUtil.deleteFile(fileEntity.getObjectKey());
        }
    }

    /**
     * 人员信息修改
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserById(UpdateUserDTO dto) {
        LambdaUpdateWrapper<YxSysUserEntity> userWrapper=new LambdaUpdateWrapper<>();
        userWrapper.set(null!=dto.getBirthday(),YxSysUserEntity::getBirthday,dto.getBirthday())
                .set(StringUtils.isNotBlank(dto.getNickName()),YxSysUserEntity::getNickName,dto.getNickName())
                .set(null!=dto.getSex(),YxSysUserEntity::getSex,dto.getSex())
                .eq(YxSysUserEntity::getUserId,dto.getUserId());
        int update = baseMapper.update(null, userWrapper);
        if(CommonConstant.ZERO==update){
            throw new BaseException("更新失败,未查询到人员信息");
        }
    }

    /**
     * 修改支付密码
     * @param dto
     */
    @Override
    public void updatePayPwdByPhone(UpdateUserPayPwdDTO dto) {
        //校验验证码
        String code = dto.getCode();
        String smdCode = (String)redisManager.get(RedisIdConstant.UPDATE_PWD_SMS_CODE + dto.getPhone());
        if(!code.equals(smdCode)){
            throw new BaseException(CommonErrorEnum.SMS_VERIFICATION_CODE);
        }
        //校验支付前后密码是否一样
        LambdaQueryWrapper<YxSysUserEntity> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(YxSysUserEntity::getPhone,dto.getPhone()).eq(YxSysUserEntity::getStatus,CommonConstant.ONE);
        YxSysUserEntity user = baseMapper.selectOne(queryWrapper);
        if(null==user){
            throw new BaseException("人员不存在或已被禁用,不能操作");
        }
        if(StringUtils.isNotBlank(user.getPayPwd())){
            //新旧密码校验
            if(Objects.equals(PasswordUtil.signUserPassword(user.getUserId(),dto.getPayPwd()), user.getPayPwd())){
                throw new BaseException("新密码不能与旧密码相同");
            }
        }
        user.setPayPwd(PasswordUtil.signUserPassword(user.getUserId(),dto.getPayPwd()));
        baseMapper.updateById(user);
    }

    /**
     * 注销账户
     * @param userId
     */
    @Override
    public void logAffAccount(Long userId) {
        YxSysUserEntity user = baseMapper.selectById(userId);
        if(null==user){
            throw new BaseException("账户不存在");
        }
        this.validataLogAff(userId);
        //注销人
        Long loginUserId = userUtil.getLoginUserId();
        String loginName = userUtil.getLoginName();
        LambdaQueryWrapper<YxLiveShopEntity> shopWapper=new LambdaQueryWrapper();
        shopWapper.eq(YxLiveShopEntity::getUserId,userId);
        List<YxLiveShopEntity> shopList = shopMapper.selectList(shopWapper);
        if(null!=shopList && !shopList.isEmpty()){
            for (YxLiveShopEntity shop:shopList) {
                YxLiveShopCancelEntity ShopCancelEntity = new YxLiveShopCancelEntity();
                BeanUtils.copyProperties(shop, ShopCancelEntity);
                ShopCancelEntity.setCancelUserId(loginUserId);
                ShopCancelEntity.setCancelUserName(loginName);
                ShopCancelEntity.setCreateTime(new Date());
                shopCancelMapper.insert(ShopCancelEntity);
            }
            //删除对应店铺信息
            shopMapper.deleteBatchIds(shopList.stream().map(shop->shop.getLiveShopId()).collect(Collectors.toList()));
        }
        //人员信息移入注销表
        YxSysUserCancelEntity userCancelEntity = new YxSysUserCancelEntity();
        BeanUtils.copyProperties(user, userCancelEntity);
        userCancelEntity.setCancelUserId(loginUserId);
        userCancelEntity.setCancelUserName(loginName);
        userCancelEntity.setCreateTime(new Date());
        userCancelMapper.insert(userCancelEntity);
        //删除人员表信息
        baseMapper.deleteById(user.getUserId());
    }

    /**
     *  //1.用户无任何未结束的订单，余额=0，2、其下店铺最后一笔订单结束时间超过30天，点击注销账号跳转二次确认页面。否则提示用户不可注销原因
     * 注销校验
     * @param userId
     */
    private void validataLogAff(Long userId) {
        //1.用户无任何未结束的订单
        LambdaQueryWrapper<YxOrderEntity> orderWapper=new LambdaQueryWrapper();
        orderWapper.eq(YxOrderEntity::getUserId,userId);
        List<Integer> statusList=new ArrayList<>();
        statusList.add(1);
        statusList.add(2);
        orderWapper.in(YxOrderEntity::getOrderStatus,statusList);
        Integer orderCnt = orderMapper.selectCount(orderWapper);
        if(orderCnt>0){
            throw  new BaseException("当前用户存在未结束的订单,不能注销");
        }
        //2、余额（视频币）=0
        LambdaQueryWrapper<YxLiveShopEntity> shopWrapper=new LambdaQueryWrapper<>();
        shopWrapper.eq(YxLiveShopEntity::getUserId,userId);
        shopWrapper.gt(YxLiveShopEntity::getLiveCoin,new BigDecimal("0"));
        Integer shopCnt = shopMapper.selectCount(shopWrapper);
        if(shopCnt>0){
            throw  new BaseException("当前用户存在店铺视频币尚未清零,不能注销");
        }
        shopWrapper.clear();
        shopWrapper.eq(YxLiveShopEntity::getUserId,userId);
        List<YxLiveShopEntity> shopList = shopMapper.selectList(shopWrapper);
        //其下店铺最后一笔订单结束时间超过30天
        orderWapper.clear();
        //查询当前时间30天前时间
        Calendar calc =Calendar.getInstance();
        calc.add(calc.DATE, -30);
        Date minDate = calc.getTime();
        orderWapper.ge(YxOrderEntity::getCompletionTime,minDate);
        orderWapper.in(YxOrderEntity::getShopId,shopList.stream().map(shop->shop.getLiveShopId()).collect(Collectors.toList()));
        orderCnt = orderMapper.selectCount(orderWapper);
        if(orderCnt>0){
            throw  new BaseException("用户店铺订单存在30天内完成的,不能注销");
        }
    }

    /**
     * 人员查询公用组件
     * @param dto
     * @return
     */
    @Override
    public PageVO<UserInfoVo> pageUserList(PageUserListDto dto) {
        List<UserInfoVo> voList=new ArrayList<>();
        Page<YxSysUserEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        LambdaQueryWrapper<YxSysUserEntity> userWrapper=new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(dto.getUserName()) && null!=dto.getUserName()){
            userWrapper.like(YxSysUserEntity::getUserName,dto.getUserName().trim());
        }
        userWrapper.exists(null!=dto.getIsLastContact() && true==dto.getIsLastContact(),"select 1 from yx_session_talk st where st.receiver_id=user_id and st.update_time  >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
        userWrapper.exists(null!=dto.getIsFollow() && true==dto.getIsFollow(),"select 1 from yx_follow yf where yf.followee_id=user_id and yf.follow_status=0");
        userWrapper.eq(YxSysUserEntity::getStatus,1);
        Page<YxSysUserEntity> pageUserList = baseMapper.selectPage(page, userWrapper);
        List<YxSysUserEntity> records = pageUserList.getRecords();
        if(null!=records && !records.isEmpty()){
            voList= BeanUtil.copyToList(records, UserInfoVo.class);
        }
        return PageUtils.get(page,voList);
    }

    @Override
    public List<UserInfoVo> getUserList() {
        List<YxSysUserEntity> userList = baseMapper.selectList(null);
        List<UserInfoVo> voList = new ArrayList<>();
        if (userList != null && !userList.isEmpty()){
            voList = BeanUtil.copyToList(userList, UserInfoVo.class);
        }
        return voList;
    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {
        YxSysUserEntity userEntity = baseMapper.selectById(userId);
        if(null == userEntity){
            throw new BaseException("用户信息不存在!");
        }
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userEntity, vo);
        return vo;
    }
}
